<template>
  <div>
    <el-card>
      <!--卡片顶部添加按钮-->
      <el-button type="primary" icon="plus" @click="addTrademark" v-has="`btn.Trademark.add`">
        添加品牌
      </el-button>
      <!--表格组件-->
      <!--
    table
    --border:可以设置表格纵向是否有边框
    table-column
    --label:某一个列表
    --width:设置这列宽度
    --align:设置这一列对齐方式
    -->
      <el-table style="margin: 10px, 0px" :border="true" :data="trademarkArr">
        <!--table-column:默认用div展示数据,想用其他标签展示就得用插槽-->
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称">
          <template #="{ row, $index }">
            <pre>{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
              v-has="`btn.Trademark.update`"
            ></el-button>

            <el-popconfirm :title="`您确定要删除${row.tmName}吗?`" width="250px" icon="Delete" @confirm="removeTradeMark(row.id)">
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                  v-has="`btn.Trademark.remove`"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--分页器组件-->
      <!--
    pagination
       v-model:current-page:设置分页器当前页码
        v-model:page-size:设置每一页展示数据条数
        page-sizes:用于设置下拉菜单数据
        background：分页器按钮是否需要背景颜色
        layout:可以设置分页器六个子组件布局调整
    -->
      <el-pagination
        @size-change="sizeChange"
        @current-change="getHasTraemark"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout=" prev, pager, next, jumper, ->,sizes, total"
        :total="total"
      />
    </el-card>
    <!--对话框组件：在添加品牌与修改已有品牌的业务时候使用结构-->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="trademark">
import { ElMessage, type UploadProps } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTraemark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark 
} from '../../../api/product/trademark/index'
import {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '../../../api/product/trademark/type'
//当前页码
let pageNo = ref<number>(1)
let limit = ref<number>(3)
//存储已有品牌的数据总数
let total = ref<number>(0)
//存储已有品牌的数据
let trademarkArr = ref<Records>([])
//控制对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false)
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//获取el-form组件实例
let formRef = ref()

//获取已有品牌的接口封装为一个函数：在任何情况下获取数据，只要调用函数即可
const getHasTraemark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTraemark(
    pageNo.value,
    limit.value,
  )

  if (result.code == 200) {
    //存储已有品牌的总个数
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
//组件挂载完毕钩子 ---发一次请求，获取第一页，一页三个已有品牌数据
onMounted(() => {
  getHasTraemark()
})

//当下拉菜单发生变化的时候触发此方法
//这个自定义事件，分页器组件会将下拉菜单选中数据返回
const sizeChange = () => {
  getHasTraemark()
}
//添加品牌按钮的回调
const addTrademark = () => {
  dialogFormVisible.value = true
  //清空上次收集的数据
  trademarkParams.id = 0
  ;(trademarkParams.tmName = ''), (trademarkParams.logoUrl = '')
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
//修改已有品牌的按钮的回调
//row即为当前已有的品牌
const updateTrademark = (row: TradeMark) => {
  //清空校验规则错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true
  //展示已有品牌的数据
  //对象合并
  Object.assign(trademarkParams, row)
}
//点击取消按钮的回调
const cancel = () => {
  dialogFormVisible.value = false
}
//点击确定按钮的回调
const confirm = async () => {
  //在你发请求之前，要对整个表单进行校验
  await formRef.value.validate()

  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //关闭对话框
    dialogFormVisible.value = false
    //再次发请求获取已有全部的品牌数据
    getHasTraemark(trademarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    //关闭对话框
    dialogFormVisible.value = false
  }
}
//钩子是在图片上传之前触发，上传文件之前可以约束文件类型与大小
//要求：上传文件格式png|jpg|gif 且小于4M
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件大小应小于4M',
    })
    return false
  }
}
//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  //response:上传图片成功服务器返回的数据
  trademarkParams.logoUrl = response.data
  //图片上传成功，清除掉校验错误信息
  formRef.value.clearValidate('logoUrl')
}
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素失去焦点时会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}

//表单检验规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'change', validator: validatorLogoUrl }],
}

//气泡确认框确定按钮的回调
const removeTradeMark=async(id:number)=>{
   let result=await reqDeleteTrademark(id);
   if(result.code==200){
    ElMessage({
      type:'success',
      message:'删除品牌成功'
    })
    getHasTraemark(trademarkArr.value.length>1?pageNo.value:pageNo.value-1)
   }else{
    ElMessage({
      type:'error',
      message:'删除品牌失败'
    })
   }
} 
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 300px;
  height: 300px;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
